const express = require('express');
const path = require('path');
// 解析html
var ejs = require('ejs');
var config = require('./config/config.js');
const { log } = require('console');

const app = express();

// 获取静态路径
app.use(express.static(__dirname + '/dist'))
app.use(express.static(__dirname + '/data'))

// 允许跨域访问
app.all('*',function(req,res,next) {
    // 允许所有ip访问
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Access-Control-Allow-Credentials", "true");

    if(req.method == 'OPTIONS'){
        res.send(200); // 让options尝试请求快速结束
    }
    else {
        next();
    }
})

// 设置模板引擎
// app.set('views', path.join(__dirname, 'dist'));
app.engine('html',ejs.__express);
app.set('view engine', 'html');

// 解析前端数据
app.use(express.json());
app.use(express.urlencoded({extended: true}));

//引入路由
require('./routes/index.js')(app);
require('./routes/files.js')(app);

app.listen(config.port,()=> {
    console.log(`服务启动成功，端口号：${config.port}`);
});
